import datetime

from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView
from common import models
from rest_framework.response import Response
import jwt
from jwt import exceptions
from common.utils import jwt_auth
from django.conf import settings
from common.extensions.auth import JwtQueryParmasAuthentication


# Create your views here.
def index(request):
    return HttpResponse('common OK')


# class LoginView(APIView):
#
#     def get(self, request):
#         return Response({"status": 'OK', 'msg': '登录成功'})
#
#     def post(self, request):
#         return Response({"status": 'OK', 'msg': '登录成功'})

# class OrderView(APIView):
#
#     def get(self, request):
#         return Response({"status": 'OK', 'msg': 'order'})
#
#     def post(self, request):
#         return Response({"status": 'OK', 'msg': '登录成功'})


class JWTLoginView(APIView):

    def get(self, request):
        print('get---- start')
        return Response({"status": 'OK', 'msg': '登录成功'})

    def post(self, request):
        print('post---- start')
        user = request.data.get('username')
        pwd = request.data.get('password')
        print(f'user={user} pwd={pwd}')
        user_obj = models.Account.objects.filter(name=user, pwd=pwd).first()
        if not user_obj:
            return Response({"status": 1000, 'msg': '用户名或者密码错误'})

        headers = {'typ': 'JWT', 'alg': 'HS256'}
        payload = {'user_id': user_obj.id,
                   'username': user_obj.name,
                   'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
                   }
        token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')

        return Response({"status": 'OK', 'data': token})


class JWTOrderView(APIView):

    def get(self, request, *args, **kwargs):
        print(f'jwt orders')
        token = request.query_params.get('token')
        print(f'token={token}')
        payload, msg = None, None
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        except exceptions.ExpiredSignatureError:
            msg = 'token 失效'
        except jwt.DecodeError:
            msg = 'token 认证失败'
        except jwt.InvalidTokenError:
            msg = '非法的token'
        if not token:
            return Response({"code": 200, 'error': '非法登录'})

        if not payload:
            return Response({'code': 1003, 'error': msg})
        print(payload)

        return Response('jwt orders')

        def post(self, request):
            return Response({"status": 'OK', 'msg': '登录成功'})


class ProLoginView(APIView):
    authentication_classes = [ ]

    def get(self, request):
        print('get---- start')
        return Response({"status": 'OK', 'msg': '登录成功'})

    def post(self, request):
        user = request.data.get('username')
        pwd = request.data.get('password')
        print(f'user={user} pwd={pwd}')
        user_obj = models.Account.objects.filter(name=user, pwd=pwd).first()
        if not user_obj:
            return Response({"status": 1000, 'msg': '用户名或者密码错误'})
        token = jwt_auth.token_create({'id': user_obj.id, 'name': user_obj.name, })

        return Response({"status": 'OK', 'data': token})


class ProOrderView(APIView):
    # authentication_classes = [JwtQueryParmasAuthentication, ]

    def get(self, request, *args, **kwargs):
        print(request.user)
        print(request.auth)

        return Response('订单列表')
